package com.xltt.vehicleControl.base;


import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.widget.Toast;

import com.xltt.vehicleControl.R;
import com.xltt.vehicleControl.activity.LauncherActivity;
import com.xltt.vehicleControl.activity.LoginActivity;
import com.xltt.vehicleControl.contants.Constants;
import com.xltt.vehicleControl.util.ActivityManager;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.xltt.vehicleControl.util.Logger;
import com.xltt.vehicleControl.util.NetWorkUtils;
import com.xltt.vehicleControl.util.RetrofitManager;
import com.xltt.vehicleControl.util.SharedPreferencesUtils;


public class MyApplication extends Application {

    private CloudPushService mCloudPushService;
    private String mAliDeviceId = "";
    private boolean mIsEngineStarted;//引擎状态

    @Override
    public void onCreate() {
        super.onCreate();
        Logger.d("MyApplication onCreate()");
        RetrofitManager.getInstance().initContext(getApplicationContext());
        // Activity 栈管理初始化
        ActivityManager.getInstance().init(this);
//        if(TextUtils.isEmpty(getAliDeviceId())){
            initCloudChannel(getApplicationContext());
//        }
    }


    /**
     * 初始化阿里云推送通道
     * @param applicationContext
     */
    public void initCloudChannel(Context applicationContext){
        Logger.d("MyApplication initCloudChannel()");
        this.createNotificationChannel();
        //初始化推送服务
        PushServiceFactory.init(applicationContext);
        //获取阿里云服务对象
         mCloudPushService = PushServiceFactory.getCloudPushService();
        //注册阿里云服务
        mCloudPushService.register(applicationContext, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                mAliDeviceId = mCloudPushService.getDeviceId();
                SharedPreferencesUtils.setParam(getApplicationContext(), LoginActivity.DEVICE_ID,mAliDeviceId);
                Logger.d("MyApplicationQWE initCloudChannel() -- > onSuccess() ,deviceId = " + mAliDeviceId);
            }
            @Override
            public void onFailed(String errorCode, String errorMessage) {
                //Toast.makeText(getApplicationContext(),"init push message faild",Toast.LENGTH_SHORT).show();
                Logger.d( "MyApplication initCloudChannel() -- > onFailed() errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
            }
        });
    }

    private String mAliasName = "";//阿里绑定别名
    public void addAlias(String aliasName){
        if(mCloudPushService != null){
            mCloudPushService.addAlias(aliasName, new CommonCallback() {
                @Override
                public void onSuccess(String s) {
                    mBindAliPush = true;
                    Logger.d("MyApplication mCommonCallback，bind ali push success");
                }

                @Override
                public void onFailed(String s, String s1) {
                    Logger.d("MyApplication mCommonCallback，bind ali push faild");
                    mBindAliPush = false;
                }
            });
            mAliasName = aliasName;
        }
    }

    public void removeAlias(){
        if(mCloudPushService != null && !TextUtils.isEmpty(mAliDeviceId)){
            mCloudPushService.removeAlias(null, new CommonCallback() {
                @Override
                public void onSuccess(String s) {
                    mBindAliPush = false;
                    Logger.d("MyApplication 清除阿里推送消息别名成功");
                }

                @Override
                public void onFailed(String s, String s1) {
                    mBindAliPush = true;
                    Logger.d("MyApplication 清除阿里推送消息别名失败");
                }
            });
            mAliasName = "";
        }
    }

    /**
     * 取消阿里云推送通道
     */
    public void cancelCloudChannel(Context context){
        if(mCloudPushService != null){
            mCloudPushService.register(context,null);
            mCloudPushService.turnOffPushChannel(new CommonCallback() {
                @Override
                public void onSuccess(String s) {
                    Logger.d("MyApplication mCommonCallback，cancel ali push success");
                    mCloudPushService = null;
                }

                @Override
                public void onFailed(String s, String s1) {
                    Logger.d("MyApplication mCommonCallback，cancel ali push faild");
                }
            });
        }
    }

    public String getAliDeviceId(){
        if(TextUtils.isEmpty(mAliDeviceId)){
            mAliDeviceId = SharedPreferencesUtils.getParam(getApplicationContext(), LoginActivity.DEVICE_ID,mAliDeviceId).toString();
            Logger.d("阿里推送初始化失败，获取上次缓存deviceId = " + mAliDeviceId);
            if(TextUtils.isEmpty(mAliDeviceId)){
                TelephonyManager tm = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
                mAliDeviceId = tm.getDeviceId();
                Logger.d("获取上次缓存deviceId为空，获取系统deviceId = " + mAliDeviceId);
            }
        }
        return mAliDeviceId;
    }

    private boolean mBindAliPush;
    public boolean bindAliPush(){
        return mBindAliPush;
    }

    /**
     * android版本大于8.0处理通知渠道
     */
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            // 通知渠道的id。
            String id = "channel";
            // 用户可以看到的通知渠道的名字。
            CharSequence name = "ProtonLink";
            // 用户可以看到的通知渠道的描述。
            String description = "ProtonLink notification";
            int importance = NotificationManager.IMPORTANCE_HIGH;
//            int importance = NotificationManager.IMPORTANCE_NONE;
            NotificationChannel mChannel = new NotificationChannel(id, name, importance);
            // 配置通知渠道的属性
            mChannel.setDescription(description);
            // 设置通知出现时的闪灯（如果 android 设备支持的话）
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            // 设置通知出现时的震动（如果 android 设备支持的话）
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            //最后在notificationmanager中创建该通知渠道
            mNotificationManager.createNotificationChannel(mChannel);
        }
    }

    public void setEngineStarted(boolean engineStarted){
        this.mIsEngineStarted = engineStarted;
    }

    public boolean isEngineStarted(){
        return mIsEngineStarted;
    }


}
